<?php
declare (strict_types=1);

namespace app\common\tool;

use app\common\model\User;
use think\facade\Log;
use WeChat\Template;

class WxTpl
{
    public function send($data, $openid, $templateId, $url = '')
    {
        try{
            if(!$openid) return ['code' => -1, 'msg'=>'发送失败'];
            //if(!$this->isFollowWx($openid)) return ['code' => -1, 'msg'=>'发送失败'];

            $sendData = array(
                'touser' => $openid,//'ootmK6G68Sw8K1EbNJm9Bm0x8oJU',
                'template_id' => $templateId, //'I18SJQjjZDV9OyuIgG89Tygn_-lsXEB00d6UZL6A3eQ',//编号43355
                'url' => '',
                "miniprogram" => [
                    'appid' => config('pay')['wechat']['appid'],//小程序APPID
                    'pagepath' => $url,
                ],
                'data' => $data,
            );

            $result = (new Template(config('pay')['wx_pub']))->send($sendData);//公众号相关配置（设置白名单）
            Log::write("发送模板消息结果：".json_encode($result));
            /*[
                "errcode" => 0
                "errmsg" => "ok"
                "msgid" => 3219666093611515904
            ]*/
            if($result['errcode'] == 0 && $result['errmsg'] == 'ok'){
                return ['code' => 1, 'msg'=>'success'];
            }

            return ['code' => -1, 'msg'=>'发送失败：'.$result['errmsg']];
        }catch (\Exception $e){
            return ['code' => -1, 'msg'=>$e->getMessage().'|errcode:'.$e->getCode()];
        }
    }

    /**
     * 是否已关注公众号
     * @param $openid
     * @return bool
     */
    public function isFollowWx($openid)
    {
        $user = (new \WeChat\User(config('pay')['wx']))->getUserInfo($openid);
        if(property_exists($user, 'subscribe') && $user->subscribe==1){
            return true;
        }
        return false;

    }
}